import datetime

from aiogram import exceptions

from loader import scheduler, bot, logger
from async_db import Database
from utils import ScheduledMessage

db = Database()


async def supper_job(j: ScheduledMessage):
    start_time = datetime.datetime.now()
    """
    """

    if j.message_id is None:
        await bot.send_message(j.chat_id, j.text)
        await db.jobs_delete(j.message_id, j.chat_id, j.text)
    elif j.message_id == 2:
        try:
            message_to_delete = await bot.send_message(j.chat_id, j.text)
            await db.jobs_add(message_to_delete.message_id, message_to_delete.chat.id, message_to_delete.text)
            await db.jobs_delete(j.message_id, j.chat_id, j.text)
            logger.success(f'{j}\n{datetime.datetime.now() - start_time}')
        except exceptions.TelegramRetryAfter as e:
            logger.error(f"{e}\n{j}")
            return
        except Exception as e:
            logger.error(f"{e}\n{j}")
            return
    else:
        try:
            await bot.delete_message(j.chat_id, j.message_id)
            logger.success(f'{j}\n{datetime.datetime.now() - start_time}')
        except exceptions.TelegramBadRequest as e:
            if 'message to delete not found' in e.message:
                logger.error(f"{e.message}\n{j}")
        await db.jobs_delete(j.message_id, j.chat_id, j.text)


async def create_tasks():
    jobs_list = await db.get_jobs()
    now = datetime.datetime.now()
    offset_second = 1
    for jobs in jobs_list:
        if offset_second % 5:
            offset_second += 1
        time = now + datetime.timedelta(seconds=offset_second)
        for j in jobs:
            scheduler.add_job(supper_job, args={j}, trigger='date', next_run_time=time)
        # if len(jobs) > 10:
        #     continue
        # logger.debug(f"{offset_second}, {len(jobs)}, {time}")
        if offset_second >= 55:
            break
        offset_second += 1
